<template>
  <div>
    <!-- 送优惠券弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :title="version===2?'赠送卡券':'赠送券'"
      width="850px"
      top="10vh"
      @close="close"
    >
      <div v-if="vipDetail" v-loading="loading" class="dialog-gift">
        <ul class="info-avatar">
          <li class="avatar">
            <img v-if="vipDetail.customer.headImg" :src="vipDetail.customer.headImg" alt>
          </li>
          <li
            class="name"
          >{{ vipDetail.member.name || vipDetail.customer.nickName }}
          </li>
        </ul>

        <div class="form">
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
            <el-form-item
              :rules="rules.couponBonus"
              :label="version===2?'赠送卡券':'赠送券'"
              prop="couponBonus"
            >
              <div class="card-coupon-container">
                <el-table
                  :data="form.couponBonus"
                  border
                  stripe
                  size="small"
                  empty-text="暂未配置"
                  style="width: 100%"
                >
                  <el-table-column prop="couponId" label="批次号" />
                  <el-table-column prop="couponName" label="卡券名称" />
                  <el-table-column prop="couponType" label="卡券类型">
                    <template slot-scope="scope">
                      {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] || "--" }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="数量" width="170px">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'couponBonus[' + scope.$index + '].amount'"
                        :rules="rules.couponBonusAmount"
                      >
                        <el-input-number
                          v-model="scope.row.amount"
                          :min="1"
                          :max="99"
                          maxlength="2"
                          label="数量"
                          style="margin-top: 18px"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                      <el-button type="text" @click="delCardCoupon(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button
                  v-if="version===2"
                  :disabled="form.couponBonus.length>=10"
                  type="text"
                  icon="el-icon-plus"
                  style="display:block"
                  @click.native.prevent="openDialogCardCouponTable"
                >增加卡券
                </el-button>
                <!--<el-button-->
                <!--  v-if="version===1"-->
                <!--  :disabled="form.couponBonus.length>=10"-->
                <!--  type="text"-->
                <!--  icon="el-icon-plus"-->
                <!--  style="display:block"-->
                <!--  @click.native.prevent="openCouponList"-->
                <!--&gt;增加券-->
                <!--</el-button>-->
                <div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="loading" size="small" round @click="hide">取 消</el-button>
        <el-button
          :disabled="loading"
          size="small"
          round
          type="primary"
          @click="handleSubmit"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹框券 -->
    <dialog-coupon-list ref="dialogCouponList" />
    <!-- 弹框券 -->
    <DialogCardCouponTable
      ref="dialogCardCouponTable"
      :card-coupon-type="['cash','discount','exchange','times','gift']"
      :has-checked-ids="hasCheckedCardCouponIds"
    />
  </div>
</template>

<script>
import DialogCouponList from '@/components/DialogCouponList'
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import { sendVipCoupon } from '@/api/vip'
import { validateCustomPositiveInt } from '@/utils/validate.js'

export default {
  components: {
    DialogCouponList,
    DialogCardCouponTable
  },
  props: {
    vipDetail: {
      type: Object,
      require: true
    }
  },
  data() {
    // 奖励优惠券
    const validateCouponBonusAmount = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback('请输入数量')
      } else if (!validateCustomPositiveInt(value, 2)) {
        callback(new Error('请输入正整数'))
      } else {
        this.$refs.form.validateField(['couponBonus'])
        callback()
      }
    }
    // 奖励优惠券
    const validateCouponBonus = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一种')
      } else if (value.length > 10) {
        callback('种类不超过10种')
      } else {
        let maxAmount = 0
        value.forEach(v => {
          if (validateCustomPositiveInt(v.amount, 2)) {
            maxAmount += v.amount
          }
        })
        if (maxAmount > 30) {
          callback('总数量不超过30张')
        } else {
          callback()
        }
      }
    }

    return {
      // 表单规则
      rules: {
        // 券列表
        couponBonus: [
          {
            type: 'array',
            required: true,
            validator: validateCouponBonus,
            trigger: ['blur', 'change']
          }
        ],
        // 优惠券数量
        couponBonusAmount: [
          {
            required: true,
            validator: validateCouponBonusAmount,
            trigger: ['blur', 'change']
          }
        ]
      },
      dialogVisible: false,
      loading: false,
      // 数据
      version: 2,
      hasCheckedCardCouponIds: [], // 已选择券id
      form: {
        couponBonus: []
      }
    }
  },
  methods: {
    open(version) {
      this.version = version
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.version = 2
      this.hasCheckedCardCouponIds = []
      this.form.couponBonus = []
      this.loading = false
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 按钮组
     */
    // 保存
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {}
          params.memberId = this.vipDetail.member.id
          const couponBonus = JSON.parse(JSON.stringify(this.form.couponBonus))
          couponBonus.forEach(v => {
            v.num = v.amount
            delete v.amount
          })
          params.coupons = couponBonus
          this.loading = true
          sendVipCoupon(params)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '赠送卡券成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.resolve && this.resolve()
              this.hide()
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    // 新增优惠券
    openCouponList() {
      this.hasCheckedCardCouponIds = []
      this.form.couponBonus.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 1).then((res) => {
        this.$refs.form.clearValidate(['couponBonus'])
        const params = Object.assign({}, res)
        this.form.couponBonus.push(params)
      })
    },

    // 新增优惠券
    openDialogCardCouponTable() {
      this.hasCheckedCardCouponIds = []
      this.form.couponBonus.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCardCouponTable.open().then((res) => {
          this.$refs.form.clearValidate(['couponBonus'])
          this.form.couponBonus = this.form.couponBonus.concat(res)
        })
      })
    },

    // 删除优惠券
    delCardCoupon(index) {
      this.form.couponBonus.splice(index, 1)
      if (this.form.couponBonus.length <= 10) {
        this.$refs.form.validateField(['couponBonus'])
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 弹框 */
.dialog-gift {
  .info-avatar {
    height: 40px;
    margin: 15px 0;

    li {
      float: left;
      margin-right: 10px;
    }

    .avatar {
      overflow: hidden;
      display: inline-block;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      border: 1px solid #e7e7e7;
    }

    .name {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: bold;
      color: $dark-font-color;
    }
  }

  /* 券列表 */
  .el-card-coupon {
    margin-bottom: 10px;
  }

  .coupon-list {
    width: 100%;
    height: 70px;
    display: inline-flex;
    align-items: center;
    justify-content: space-between;

    .coupon-info {
      color: #606266;
      margin-right: 30px;
      line-height: 1.5;
    }
  }
}
</style>
